package com.huaao.micropolice.core.service.system.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huaao.micropolice.core.model.system.Menu;
import com.huaao.micropolice.core.repository.system.MenuDao;
import com.huaao.micropolice.core.service.system.MenuService;

@Service
@Transactional
public class MenuServiceImpl implements MenuService{
	
	@Autowired
	private MenuDao menuDao;

	@Override
	public List<Menu> findRoot() {
		return menuDao.findRoot();
	}

	@Override
	public void save(Menu menu){
		if(StringUtils.isBlank(menu.getId())){
			add(menu);
		}else{
			edit(menu);
		}
	}
	
	private void edit(Menu menu) {
		Menu old = menuDao.load(menu.getId());
		Menu parent = menu.getParent();
		old.setName(menu.getName());
		old.setSort(menu.getSort() == null ? 0 : menu.getSort());
		old.setPermission(menu.getPermission());
		old.setIcon(menu.getIcon());
		old.setUrl(menu.getUrl());
		
		Integer level = 0;
		if(parent == null || StringUtils.isBlank(parent.getId())){
			level = 0;
			old.setParent(null);
		}else{
			parent = menuDao.load(parent.getId());
			level = parent.getLevel() + 1;
			old.setParent(parent);
		}
		menu.setLevel(level);
		menuDao.update(old);
	}

	private void add(Menu menu) {
		Menu parent = menu.getParent();
		Integer level = 0;
		if(parent == null || StringUtils.isBlank(parent.getId())){
			menu.setParent(null);
		}else{
			parent = menuDao.load(parent.getId());
			level = parent.getLevel() + 1;
		}
		if(menu.getSort() == null){
			menu.setSort(0);
		}
		menu.setLevel(level);
		menuDao.save(menu);
	}

	@Override
	public List<Menu> findAll() {
		return menuDao.findAll();
	}

	@Override
	public Menu load(String id) {
		return menuDao.load(id);
	}

	@Override
	@Transactional
	public String dels(String... ids) {
		String msg = "操作成功";
		for(String id : ids){
			Menu menu = menuDao.load(id);
			if(menu.getChildren().size() > 0){
				msg = "菜单下有子菜单无法删除!";
				break;
			}
			menuDao.delete(menu);
		}
		return msg;
	}
}
